package com.xhwl.logistics.service.impl.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.logistics.bo.cent.VehicleIntegratedConfigBO;
import com.xhwl.logistics.bo.cent.VehicleParkingInfoBO;
import com.xhwl.logistics.component.SignForJieShun;
import com.xhwl.logistics.dto.http.BusinessJieShunDTO;
import com.xhwl.logistics.dto.http.CarportJieShunDTO;
import com.xhwl.logistics.dto.http.ParkingLotInfoJieShunDTO;
import com.xhwl.logistics.dto.http.ResponseCommonJieShunDTO;
import com.xhwl.logistics.dto.http.TokenJieShunDTO;
import com.xhwl.logistics.dto.http.query.QueryCarportJieShunDTO;
import com.xhwl.logistics.dto.http.query.QueryCommonJieShunDTO;
import com.xhwl.logistics.dto.http.query.QueryParameterJieShunDTO;
import com.xhwl.logistics.dto.http.query.QueryParkingLotInfoJieShunDTO;
import com.xhwl.logistics.dto.http.query.QueryTokenJieShunDTO;
import com.xhwl.logistics.service.impl.redis.VehicleTokenRedisServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.Map;
import java.util.Objects;

//@Service
public class JieShunHttpServiceImpl {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SignForJieShun signForJieShun;

    @Autowired
    private VehicleTokenRedisServiceImpl vehicleTokenRedisService;

    private void jieShunResponseHandle(ResponseCommonJieShunDTO responseCommonJieShunDTO) {
        if (0!=responseCommonJieShunDTO.getResultCode()) {
            throw new BusinessException("访问捷顺的http接口，返回的resultCode不是代表成功的0，resultCode:" + responseCommonJieShunDTO.getResultCode() + "，message:" + responseCommonJieShunDTO.getMessage());
        }
    }

    private <T extends QueryParameterJieShunDTO<?>> QueryCommonJieShunDTO getQueryCommonJieShunDTO(VehicleIntegratedConfigBO vehicleIntegratedConfigBO, T data) {
        VehicleParkingInfoBO vehicleParkingInfoBO = vehicleIntegratedConfigBO.getVehicleParkingInfoBO();
        QueryCommonJieShunDTO queryCommonJieShunDTO = new QueryCommonJieShunDTO();
        queryCommonJieShunDTO.setCid(vehicleParkingInfoBO.getAppId());
        queryCommonJieShunDTO.setTn(vehicleTokenRedisService.getTokenByProjectId(vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId()));
        queryCommonJieShunDTO.setV(vehicleParkingInfoBO.getVersion());
        queryCommonJieShunDTO.setP(JSON.toJSONString(data));
        queryCommonJieShunDTO.setSn(signForJieShun.sign(data, vehicleParkingInfoBO.getAppSecret()));
        return queryCommonJieShunDTO;
    }

    public TokenJieShunDTO getToken(VehicleIntegratedConfigBO vehicleIntegratedConfigBO) {
        final String login = "/login";

        VehicleParkingInfoBO vehicleParkingInfoBO = vehicleIntegratedConfigBO.getVehicleParkingInfoBO();
        QueryTokenJieShunDTO queryTokenJieShunDTO = new QueryTokenJieShunDTO(vehicleParkingInfoBO.getAppId(), vehicleParkingInfoBO.getUser(), vehicleParkingInfoBO.getPassword());

        LinkedMultiValueMap<String, String> linkedMultiValueMap = new LinkedMultiValueMap<>();
        linkedMultiValueMap.setAll(JSON.parseObject(JSON.toJSONString(queryTokenJieShunDTO), new TypeReference<Map<String, String>>() {}));

        String uriString = UriComponentsBuilder.fromHttpUrl(vehicleParkingInfoBO.getHost() + login).queryParams(linkedMultiValueMap).toUriString();

        //        TokenJieShunDTO tokenJieShunDTO = restTemplate.getForObject(uriString, TokenJieShunDTO.class);
        String responseString = restTemplate.getForObject(uriString, String.class);
        TokenJieShunDTO tokenJieShunDTO = JSON.parseObject(responseString, TokenJieShunDTO.class);

        jieShunResponseHandle(Objects.requireNonNull(tokenJieShunDTO));

        return tokenJieShunDTO;
    }

    public ParkingLotInfoJieShunDTO getParkingLotInfo(VehicleIntegratedConfigBO vehicleIntegratedConfigBO) {
        final String business = "/as";
        final String serviceId = "3c.park.queryparkinfo";

        VehicleParkingInfoBO vehicleParkingInfoBO = vehicleIntegratedConfigBO.getVehicleParkingInfoBO();

        QueryCommonJieShunDTO queryCommonJieShunDTO = getQueryCommonJieShunDTO(vehicleIntegratedConfigBO, new QueryParameterJieShunDTO<>(serviceId, new QueryParkingLotInfoJieShunDTO(vehicleParkingInfoBO.getParkId())));
        LinkedMultiValueMap<String, String> linkedMultiValueMap = new LinkedMultiValueMap<>();
        linkedMultiValueMap.setAll(JSON.parseObject(JSON.toJSONString(queryCommonJieShunDTO), new TypeReference<Map<String, String>>() {}));

//        String uriStringTest = UriComponentsBuilder.fromHttpUrl(vehicleParkingInfoBO.getHost() + business).queryParams(linkedMultiValueMap).toUriString();
//        String responseStringTest = restTemplate.getForObject(uriStringTest, String.class);

        URI uri = UriComponentsBuilder.fromHttpUrl(vehicleParkingInfoBO.getHost() + business).queryParams(linkedMultiValueMap).build().toUri();
        String responseString = restTemplate.getForObject(uri, String.class);

        BusinessJieShunDTO businessJieShunDTO = JSON.parseObject(responseString, BusinessJieShunDTO.class);
        jieShunResponseHandle(Objects.requireNonNull(businessJieShunDTO));

        JSONArray dataItems = businessJieShunDTO.getDataItems();
        if (1!=dataItems.size()) {
            throw new BusinessException("捷顺获取车场信息的http接口时，解析仅支持一个长度的车场信息的返回结果，因此目前http返回结果长度不为1");
        }
        return dataItems.getJSONObject(0).getObject("attributes", ParkingLotInfoJieShunDTO.class);
    }

    public CarportJieShunDTO getCarport(VehicleIntegratedConfigBO vehicleIntegratedConfigBO) {
        final String business = "/as";
        final String serviceId = "3c.park.queryparkspace";

        VehicleParkingInfoBO vehicleParkingInfoBO = vehicleIntegratedConfigBO.getVehicleParkingInfoBO();

        QueryCommonJieShunDTO queryCommonJieShunDTO = getQueryCommonJieShunDTO(vehicleIntegratedConfigBO, new QueryParameterJieShunDTO<>(serviceId, new QueryCarportJieShunDTO(vehicleParkingInfoBO.getParkId())));
        LinkedMultiValueMap<String, String> linkedMultiValueMap = new LinkedMultiValueMap<>();
        linkedMultiValueMap.setAll(JSON.parseObject(JSON.toJSONString(queryCommonJieShunDTO), new TypeReference<Map<String, String>>() {}));

        URI uri = UriComponentsBuilder.fromHttpUrl(vehicleParkingInfoBO.getHost() + business).queryParams(linkedMultiValueMap).build().toUri();
        String responseString = restTemplate.getForObject(uri, String.class);

        BusinessJieShunDTO businessJieShunDTO = JSON.parseObject(responseString, BusinessJieShunDTO.class);
        jieShunResponseHandle(Objects.requireNonNull(businessJieShunDTO));

        JSONArray dataItems = businessJieShunDTO.getDataItems();
        if (1!=dataItems.size()) {
            throw new BusinessException("捷顺获取车位信息的http接口时，解析仅支持一个长度的车位信息的返回结果，因此目前http返回结果长度不为1");
        }
        return dataItems.getJSONObject(0).getObject("attributes", CarportJieShunDTO.class);
    }

}
